/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.buzzwords.behaviors;

import com.buzzwords.exceptions.DuplicateEntryException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author potlow
 */
public abstract class DatabaseBehavior {
    protected EntityManagerFactory emf;

    public void createEmf(String persistenceUnit) {
        emf = Persistence.createEntityManagerFactory(persistenceUnit);
    }

    public abstract boolean create(Object value) throws DuplicateEntryException;
    public abstract List<Object> read(Object value);
    public abstract boolean update(Object value);
    public abstract boolean delete(Object value);

    protected boolean persist(Object object) {
        boolean didPersist = true;
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
            didPersist = false;
        } finally {
            em.close();
        }
        merge(object);
        return didPersist;
    }

    protected boolean remove(Object object) {
        boolean didRemove = true;
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.remove(em.merge(object));
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
            didRemove = false;
        } finally {
            em.close();
        }
        return didRemove;
    }

    protected boolean merge(Object object) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.merge(object);
        em.getTransaction().commit();
        em.close();
        return true;
    }
}
